<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 添加角色 -->
    <el-button type="primary"
               @click="addRolesDialogVisible=true">添加角色</el-button>

    <!-- 卡片区域 -->
    <el-card>
      <el-table :data="rolesList"
                border
                stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
                    v-for="(item1, i1) in scope.row.children"
                    :key="item1.id">
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable
                        @close="removeRightsById(scope.row, item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级权限 -->
              <el-col :span="19">
                <el-row :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                        v-for="(item2, i2) in item1.children"
                        :key="item2.id">
                  <!-- 二级权限      -->
                  <el-col :span="7">
                    <el-tag type="success"
                            closable
                            @close="removeRightsById(scope.row, item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="12">
                    <el-tag type="warning"
                            v-for="item3 in item2.children"
                            :key="item3.id"
                            closable
                            @close="removeRightsById(scope.row, item3.id)">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"
                         label="#">
        </el-table-column>
        <el-table-column prop="roleName"
                         label="角色名称">
        </el-table-column>
        <el-table-column prop="roleDesc"
                         label="角色描述">
        </el-table-column>
        <el-table-column label="操作"
                         width="290px">
          <template v-slot="scope">
            <!-- 编辑按钮 -->
            <el-button type="primary"
                       icon="el-icon-edit"
                       size="mini"
                       @click="showEditRolesDialog(scope.row.id)">编辑</el-button>
            <!-- 删除按钮 -->
            <el-button type="danger"
                       icon="el-icon-delete"
                       size="mini"
                       @click="removeRolesById(scope.row.id)">删除</el-button>
            <!-- 分配权限按钮 -->
            <el-button type="warning"
                       icon="el-icon-setting"
                       size="mini"
                       @click="showSetRightDialog(scope.row)">分配权限</el-button>

          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色"
               :visible.sync="addRolesDialogVisible"
               width="50%"
               @close="addRolesDialogClose()">
      <!-- 内容主体区域 -->
      <el-form :model="addRolesForm"
               :rules="formRules"
               ref="addRolesFormRef"
               label-width="80px">
        <el-form-item label="角色名称"
                      prop="roleName">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述"
                      prop="roleDesc">
          <el-input v-model="addRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer">
        <el-button @click="addRolesDialogVisible=false">取 消</el-button>
        <el-button type="primary"
                   @click="addRoles()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改角色对话框 -->
    <el-dialog title="修改角色信息"
               :visible.sync="editRolesDialogVisible"
               width="50%"
               @close="editRolesDialogClose()">
      <!-- 内容主体区域 -->
      <el-form :model="editRolesForm"
               :rules="formRules"
               ref="editRolesFormRef"
               label-width="80px">
        <el-form-item label="角色名"
                      prop="roleName">
          <el-input v-model="editRolesForm.roleName"
                    disabled></el-input>
        </el-form-item>
        <el-form-item label="角色描述"
                      prop="roleDesc">
          <el-input v-model="editRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer">
        <el-button @click="editRolesDialogVisible=false">取 消</el-button>
        <el-button type="primary"
                   @click="editRolesInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限的对话框 -->
    <el-dialog title="分配权限"
               :visible.sync="setRightDialogVisible"
               width="50%"
               @close="setRightDialogClosed">
      <!-- 树形控件 -->
      <el-tree :data="rightsList"
               :props="treeProps"
               show-checkbox
               node-key="id"
               default-expand-all
               :default-checked-keys="defKeys"
               ref="treeRef"></el-tree>
      <span>
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="assignRight">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { getRolesData, addRolesData, queryRolesData, submitRolesData, deleteRole, deleteRights, getRightsList, updateRights } from '../../network/roles';
export default {
  name: 'Roles',
  data () {
    return {
      //角色列表
      rolesList: [],
      //控制添加角色对话框的显示与隐藏
      addRolesDialogVisible: false,
      //控制修改角色对话框的显示与隐藏
      editRolesDialogVisible: false,
      //控制修改分配权限对话框的显示与隐藏
      setRightDialogVisible: false,
      //添加角色的表单数据
      addRolesForm: {
        roleName: '',
        roleDesc: ''
      },
      //编辑角色的表单数据
      editRolesForm: {
      },
      //表单的用户规则
      formRules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
        ],
        roleDesc: [
          { required: true, message: '请描述下角色', trigger: 'blur' },
        ],
      },
      //所有权限的数据
      rightsList: [],
      //树形控件的属性绑定对象
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      //默认选中的节点Id值数组
      defKeys: [],
      //当前即将分配权限的角色id
      roleId: '',
    }
  },
  created () {
    this.getRolesList();
  },
  methods: {
    //获取角色列表
    async getRolesList () {
      const res = await getRolesData();
      //console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data;
    },

    //添加角色对话框关闭时重置表单
    addRolesDialogClose () {
      this.$refs.addRolesFormRef.resetFields();
    },

    //编辑角色对话框关闭时重置表单
    editRolesDialogClose () {
      this.$refs.editRolesFormRef.resetFields();
    },

    //添加角色 
    addRoles () {
      //表单校验是否通过
      this.$refs.addRolesFormRef.validate(async valid => {
        //console.log(valid);
        if (!valid) return;
        const res = await addRolesData(this.addRolesForm);
        //console.log(res);
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败');
        }
        this.addRolesDialogVisible = false;
        this.getRolesList();
        this.$message.success('添加角色成功');
      })
    },

    //展示编辑角色的对话框
    async showEditRolesDialog (id) {
      this.editRolesDialogVisible = true;
      const res = await queryRolesData(id);
      //console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('查询角色信息失败');
      }
      this.editRolesForm = res.data;
      // console.log(this.editRolesForm);
    },

    //修改角色信息并提交
    async editRolesInfo () {
      this.$refs.editRolesFormRef.validate(async valid => {
        if (!valid) return;
        const res = await submitRolesData(this.editRolesForm);
        if (res.meta.status !== 200) {
          return this.$message.error('更新角色失败');
        }
        this.editRolesDialogVisible = false;
        this.getRolesList();
        this.$message.success('更新角色成功');
      })
    },

    //删除角色
    async removeRolesById (id) {
      //弹框提示角色是否要删除
      const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err);
      //console.log(confirmResult);
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了修改');
      }
      await deleteRole(id);
      this.getRolesList();
      this.$message.success('删除角色成功');
    },

    //根据Id删除对应的权限
    async removeRightsById (roleInfo, rightId) {
      //弹框提示权限是否要删除
      const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err);
      //console.log(confirmResult);
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了修改');
      }
      //console.log('确认了修改');
      const res = await deleteRights(roleInfo.id, rightId);
      roleInfo.children = res.data;
      this.$message.success('删除权限成功');
    },

    //展示分配权限的对话框
    async showSetRightDialog (role) {
      this.roleId = role.id;
      const res = await getRightsList();
      if (res.meta.status !== 200) {
        this.$message.error('获取权限列表失败');
      }
      this.rightsList = res.data;
      //console.log(this.rightsList);

      //获取三级节点的id
      this.getLeafKeys(role, this.defKeys);

      this.setRightDialogVisible = true;
    },

    //获取角色下所有三级权限的id
    getLeafKeys (node, arr) {
      //如果是三级节点
      if (!node.children) {
        return arr.push(node.id);
      }

      //如果不是三级节点
      node.children.forEach(item => this.getLeafKeys(item, arr));
    },

    //监听分配权限对话框的关闭事件
    setRightDialogClosed () {
      this.defKeys = [];
    },

    //分配角色权限
    async assignRight () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()
      ];
      //console.log(keys);
      const idStr = keys.join(',');
      // console.log(idStr);
      const res = await updateRights(this.roleId, { rids: idStr });
      //console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败');
      }
      this.$message.success('分配权限成功');
      this.getRolesList();
      this.setRightDialogVisible = false;
    }

  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.el-card {
  margin-top: 20px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>